// pages/user-time-wage/user-time-wage.js
const app = getApp()

Page({
  data: {
    timeWageData: null,
    timeWageHistory: [],
    loading: true,
    refreshing: false,
    currentMonth: '',
    selectedMonth: ''
  },

  onLoad() {
    // 设置当前月份
    const now = new Date()
    const currentMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
    
    this.setData({
      currentMonth: currentMonth,
      selectedMonth: currentMonth
    })
    
    this.loadTimeWageData()
  },

  onShow() {
    this.loadTimeWageData()
  },

  onPullDownRefresh() {
    this.setData({
      refreshing: true
    })
    this.loadTimeWageData().then(() => {
      wx.stopPullDownRefresh()
      this.setData({
        refreshing: false
      })
    })
  },

  // 加载时间工资数据
  loadTimeWageData() {
    this.setData({
      loading: true
    })

    return app.userRequest({
      url: '/getTimeWageData',
      data: {
        month: this.data.selectedMonth
      }
    }).then((res) => {
      this.setData({
        timeWageData: res.data,
        loading: false
      })
    }).catch((err) => {
      console.error('获取时间工资数据失败:', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '获取时间工资数据失败',
        icon: 'none'
      })
    })
  },

  // 加载时间工资历史
  loadTimeWageHistory() {
    app.userRequest({
      url: '/getTimeWageHistory'
    }).then((res) => {
      this.setData({
        timeWageHistory: res.data || []
      })
    }).catch((err) => {
      console.error('获取时间工资历史失败:', err)
    })
  },

  // 选择月份
  onMonthChange(e) {
    this.setData({
      selectedMonth: e.detail.value
    })
    this.loadTimeWageData()
  },

  // 查看时间工资详情
  viewTimeWageDetail(e) {
    const month = e.currentTarget.dataset.month
    this.setData({
      selectedMonth: month
    })
    this.loadTimeWageData()
  },

  // 导出时间工资单
  exportTimeWage() {
    if (!this.data.timeWageData) {
      wx.showToast({
        title: '暂无时间工资数据',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '导出中...'
    })

    app.userRequest({
      url: '/exportTimeWage',
      method: 'POST',
      data: {
        month: this.data.selectedMonth
      }
    }).then((res) => {
      wx.hideLoading()
      if (res.data && res.data.download_url) {
        // 下载文件
        wx.downloadFile({
          url: res.data.download_url,
          success: (downloadRes) => {
            wx.openDocument({
              filePath: downloadRes.tempFilePath,
              success: () => {
                wx.showToast({
                  title: '导出成功',
                  icon: 'success'
                })
              }
            })
          }
        })
      } else {
        wx.showToast({
          title: '导出失败',
          icon: 'none'
        })
      }
    }).catch((err) => {
      wx.hideLoading()
      console.error('导出时间工资单失败:', err)
      wx.showToast({
        title: '导出失败',
        icon: 'none'
      })
    })
  }
})
